<template>
  <div class="app-container">

    <el-row v-permission="['sys:user:view']">
      <el-button @click="showOps" size="small" type="primary" icon="el-icon-s-operation" round>更多操作</el-button>
      <el-button v-permission="['sys:user:roleassign']" @click="showAssignDialog" v-show="flagShowMore" size="small" type="success" round>分配角色</el-button>
      <el-button v-permission="['sys:user:add']" @click="showAddDialog" v-show="flagShowMore" icon="el-icon-plus" size="small" type="success" round>新增</el-button>
    </el-row>

    <el-table
      :data="tableData.filter(data => !search
        || data.username.toLowerCase().includes(search.toLowerCase())
        || data.nickName.toLowerCase().includes(search.toLowerCase())
      )"
      :height="tableHeight"
      row-key="id"
      ref="dataTable"
      v-loading="flagTableLoading"
      stripe
      element-loading-text="加载中"
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column v-if="flagShowMore" type="selection" :reserve-selection="true" min-width="50"/>
      <el-table-column type="index" label="序号" min-width="50"/>
      <el-table-column label="账号" prop="username" min-width="90"/>
      <el-table-column label="别称" prop="nickName" min-width="100"/>
      <el-table-column label="状态" prop="status" min-width="60"
                       :formatter="formatterStatus"
                       :filters="[{text: '启用', value: 1},{text: '禁用', value: 0}]"
                       :filter-method="handleFilterStatusTableData"/>
      <el-table-column label="邮箱" prop="email" min-width="150"/>
      <el-table-column label="创建时间" prop="createTime" min-width="180"/>
      <el-table-column label="备注" prop="note" min-width="80"/>
      <el-table-column label="操作" align="center" fixed="right" min-width="200">
        <template slot="header" slot-scope="scope">
          <el-input v-model="search" size="mini" placeholder="输入关键字搜索(只能查询当前页)"/>
        </template>
        <template slot-scope="scope">
          <el-button @click="handleView(scope.$index, scope.row)" type="primary" size="mini">查看</el-button>
          <el-button v-permission="['sys:user:update']" :disabled="scope.row.username === 'ADMIN'" @click="handleEdit(scope.$index, scope.row)" type="warning" size="mini">编辑</el-button>
          <el-popconfirm title="删除后无法恢复，确定删除吗？" icon="el-icon-info" icon-color="red"
              @confirm="handleDelete(scope.$index, scope.row)">
            <el-button v-permission="['sys:user:del']" :disabled="scope.row.username === 'ADMIN'" slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :page-count="totalPage"
      :total="total"
      layout="->, total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <el-dialog title="账号信息"
               :visible.sync="flagDialogInfoVisible">
      <el-descriptions border>
        <el-descriptions-item label="账号">{{form.username}}</el-descriptions-item>
        <el-descriptions-item label="别名">{{form.nickName}}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{form.email}}</el-descriptions-item>
        <el-descriptions-item label="状态">{{formatterStatus('','',form.status)}}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{form.note}}</el-descriptions-item>
        <el-descriptions-item label="所属角色">{{form.roleStr}}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="flagDialogInfoVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="flagDialogAddVisible? '新增' :'编辑'"
               :visible="flagDialogEditVisible || flagDialogAddVisible"
               @close="closeDialog">
      <el-form :model="form" ref="dialogForm" :rules="formRules">
        <el-form-item label="账号" prop="username" :label-width="formLabelWidth">
          <el-input v-model="form.username" :disabled="!flagDialogAddVisible" autocomplete="off"/>
        </el-form-item>
        <el-form-item v-if="flagDialogAddVisible" prop="password" label="密码" :label-width="formLabelWidth">
          <el-input show-password placeholder="必须包含大小写字母和数字的组合，不能使用特殊字符，长度在6-8" v-model="form.password" />
        </el-form-item>
        <el-form-item v-if="flagDialogAddVisible" prop="checkPass" label="确认密码" :label-width="formLabelWidth">
          <el-input show-password placeholder="请确认密码" v-model="form.checkPass"/>
        </el-form-item>
        <el-form-item label="别名" :label-width="formLabelWidth">
          <el-input v-model="form.nickName"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
          <el-input type="email" v-model="form.email"/>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-select v-model="form.status" placeholder="账号状态">
            <el-option key="v1" label="启用" :value="1"/>
            <el-option key="v0" label="禁用" :value="0"/>
          </el-select>
        </el-form-item>
        <el-form-item label="所属角色" :label-width="formLabelWidth">
          <el-select v-model="roleActiveArr" multiple filterable default-first-option
            placeholder="请选择角色" style="display: block">
            <el-option v-for="item in roleArr" :key="'role'+item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.note"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="handleFromConfirm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="多用户分配角色" width="30%" :visible.sync="flagDialogRoleVisible">
      <el-select v-model="multipleRoleActive" filterable default-first-option
                 placeholder="请选择角色" style="display: block">
        <el-option v-for="item in roleArr" :key="'roleM'+item.id" :label="item.name" :value="item.id" />
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="flagDialogRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAssignRole">确 定</el-button>
      </div>
    </el-dialog>

  </div>

</template>

<script>

  import permission from '@/directive/permission/index' // 权限判断指令
  import {isNotEmpty,validPassword} from "@/utils/validate";

  export default {
  directives: { permission },
  data() {

    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else if(!validPassword(value)){
        callback(new Error('必须包含大小写字母和数字的组合，不能使用特殊字符，长度在6-8'))
      } else {
        if (this.form.checkPass !== '') {
          this.$refs.dialogForm.validateField('checkPass');
        }
        callback();
      }
    }

    let validateCheckPass = (rule, value, callback) =>{
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    }

    return {
      flagDialogEditVisible: false,
      flagDialogRoleVisible: false,
      flagDialogAddVisible: false,
      flagDialogInfoVisible: false,
      flagShowMore: false,
      flagTableLoading: false,
      formLabelWidth: '120px',
      tableData: [],
      search: '',
      pageNum: 1,
      pageSize: 10,
      totalPage: 0,
      total: 0,
      // windowWidth: document.documentElement.clientWidth,  //实时屏幕宽度
      tableHeight: document.body.clientHeight-150,   //实时屏幕高度
      form: {
        username: '',
        nickName: '',
        icon: '',
        email: '',
        note: '',
        roles:[{id:0}],
        status: ''
      },
      formRules:{
        username: [{ required: true, message: '请输入账号', trigger: 'blur' },
          {type:'string',message: '只允许字母数字和下划线,长度4-10',min:4,max:10,pattern: /^\w+$/,trigger: 'blur'}],
        email: [{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validatePass, trigger: ['blur','change'] }],
        checkPass: [{ required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validateCheckPass, trigger: 'blur' }]

      },
      multipleSelectionArr: [],
      multipleRoleActive: undefined,
      roleArr: [],
      roleActiveArr:[]
    }
  },
  created() {
    this.fetchData()
    this.fetchRoles()
  },
  methods: {
    fetchRoles() {
      this.getRequest("/role/listRoleForAdmin").then(res => {
        if (res.code === 200) {
          this.roleArr = res.content
        }else{
          this.$message({message: res.error, type: 'error'})
        }
      }).catch((error) => {
        this.$message({message: error, type: 'error'})
        this.flagTableLoading = false
      })
    },
    fetchData() {
      this.flagTableLoading = true
      this.getRequest("/admin/list",{pageNum:this.pageNum,pageSize:this.pageSize}).then(res =>{
        if (res.code === 200) {
          this.tableData = res.content.list
          this.pageNum = res.content.pageNum
          this.pageSize = res.content.pageSize
          this.totalPage = res.content.totalPage
          this.total = res.content.total
        }
        this.flagTableLoading = false;
      }).catch((error) => {
        this.$message({message: error, type: 'error'})
        this.flagTableLoading = false
      })
    },
    formatterStatus(row,column,cellValue,index){
      return cellValue ===1 ? "启用":"禁用"
    },
    handleView(index, row) {
      this.form = row
      let roles = this.cloneDeep(row.roles)
      this.form.roleStr = roles.map(obj=>obj.name)
      this.flagDialogInfoVisible = true
    },
    handleEdit(index, row) {
      this.form = this.cloneDeep(row)
      this.roleActiveArr = this.form.roles.map(obj=>obj.id)
      this.flagDialogEditVisible = true
    },
    handleDelete(index, row) {
      this.deleteRequest("/admin/"+row.id).then(res =>{
        if (res.code === 200) {
          this.$message({message: "删除成功", type: 'success'})
          this.fetchData()
        }else{
          this.$message({message: "删除失败", type: 'error'})
        }
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.fetchData()
    },
    handleFromConfirm(){
      this.$refs["dialogForm"].validate(valid => {
        if (valid) {
          if (isNotEmpty(this.form.password)) {
            this.form.roles = this.roleActiveArr.map(obj=>{return {id:obj}})
            this.postRequest("/admin/add",this.form).then(res => {
              if (res.code === 200) {
                this.$message({message: "添加成功", type: 'success'})
                this.flagDialogAddVisible = false
                this.fetchData()
              }else{
                this.$message({message: "添加失败", type: 'error'})
              }
            });
          }else{
            this.form.roles = this.roleActiveArr.map(obj=>{return {id:obj}});
            this.putRequest("/admin",this.form).then(res => {
              if (res.code === 200) {
                this.$message({message: "更新成功", type: 'success'})
                this.flagDialogEditVisible = false
                this.fetchData()
              }else{
                this.$message({message: "更新失败", type: 'error'})
              }
            })
          }
        }
      })
    },
    closeDialog(){
      this.flagDialogAddVisible = false
      this.flagDialogEditVisible = false
    },
    showAddDialog(){
      this.roleActiveArr = []
      this.form = {
        username: '',
        nickName: '',
        password: '',
        checkPass: '',
        icon: '',
        email: '',
        note: '',
        roles:[],
        status: 1
      }
      this.flagDialogAddVisible = true
    },
    showAssignDialog(){
      this.multipleRoleActive = undefined
      this.flagDialogRoleVisible = true
    },
    showOps(){
      this.flagShowMore = !this.flagShowMore
      this.$refs.dataTable.clearSelection();
    },
    handleFilterStatusTableData(value, row, column){
      let property = column['property'];
      return row[property] === value
    },
    handleSelectionChange(val) {
      this.multipleSelectionArr = val;
    },
    handleAssignRole(){
      if (isNotEmpty(this.multipleSelectionArr) && isNotEmpty(this.multipleRoleActive)) {

        let paramArr = this.multipleSelectionArr.map(obj =>{
          return {adminId: obj.id,roleId: this.multipleRoleActive}
        })

        this.postRequest("/admin/updateAdminRole",paramArr).then(res => {
          if (res.code === 200) {
            this.$message({message: "更新成功", type: 'success'})
            this.fetchData()
            this.showOps()
          }else{
            this.$message({message: "更新失败", type: 'error'})
          }
        })
        this.flagDialogRoleVisible = false
      }else{
        this.$message({message: "请先选择用户", type: 'warning'})
      }
    }
  }
}
</script>
